﻿using Common;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Equipment;
using MvvmDemo.Model;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MvvmDemo.ViewModel
{
    public partial class MainWindowViewModel:ObservableObject
    {
        [ObservableProperty]
        [NotifyPropertyChangedFor(nameof(Caption))]
        private string? title = "Hello,World";

        [ObservableProperty]
        private int count;

        [ObservableProperty]
        private bool? mState;

        [ObservableProperty]
        private ObservableCollection<LogModel> logModelsv = new ObservableCollection<LogModel>();

        public MitsubishiPLC Fx3u {  get; set; }
        public string Caption
        {
            get { return $"Title: {Title}"; }
        }

        [ObservableProperty]
        [NotifyCanExecuteChangedFor(nameof(BtnClickCommand))]
        private bool isEnabled;

        [RelayCommand(CanExecute =nameof(IsEnabled))]
        private void BtnClick()
        {
            if(Fx3u.IsOpen)
            {
                LogWrite("PLC已经打开");
            }
            else
            {
                LogWrite("PLC还未打开");
            }

        }

        [RelayCommand]
        private void Mread()
        {
            bool ans;
            if(Fx3u.MRead("M100", out ans))
            {
                LogWrite("M寄存器读取成功");
            }
            else
            {
                LogWrite("M寄存器读取失败");
            }
            MState = ans;
        }

        public MainWindowViewModel()
        {
          //  IsEnabled = true;
            Fx3u = MitsubishiPLC.Instance;
            try
            {
                if (Fx3u.Open())
                {
                    LogWrite("PLC通讯组件打开成功");
                }
                else
                {
                    LogWrite($"PLC通讯组件打开失败，已经打开或遇到错误:{Fx3u.ErrCode}");
                    
                }
            }
            catch (Exception ex)
            {
                LogWrite(ex.Message,3);
            }

            
        }
        private void LogWrite(string str,int flag = 1)
        {
            LogModel LM = new LogModel();
            LM.Time = DateTime.Now;
            LM.LogContext = str;
            LogModelsv.Add(LM);
            if (LogModelsv.Count >= 5)
                logModelsv.RemoveAt(0);
            switch(flag)
            {
                case 1:AppLog.WriteInfo(str);break;
                case 2:AppLog.WriteWarn(str);break;
                case 3:AppLog.WriteError(str);break;
                default:
                    break;
            }

        }
    }
}
